from django.core.management.base import BaseCommand
from django.urls import URLPattern, URLResolver, include
from django.apps import apps


class Command(BaseCommand):
    help = 'List all URLs in the project'

    def handle(self, *args, **options):
        for app in apps.get_app_configs():
            # 获取每个app的urlconf模块
            urlconf_module = app.name + '.urls'
            try:
                # 尝试获取urlconf模块
                url_module = __import__(urlconf_module, {}, {}, [''])
            except ImportError:
                continue
            # 遍历所有URLPattern和URLResolver对象
            print('===== %s ======' % app)
            for url in url_module.urlpatterns:
                if isinstance(url, URLPattern) and url.lookup_str:
                    app_name = url.lookup_str
                    self.stdout.write(url.pattern.regex.pattern)
                elif isinstance(url, URLResolver):
                    include_url = url.pattern.regex.pattern
                    for inner_url in url.url_patterns:
                        self.stdout.write(include_url + inner_url.pattern)
